<?php
/**
 * 活动管理
 * 
 * @author  Lee <a605333742@gmail.com>
 * @time    2016-04-29
 */
namespace Home\Controller;

class ClubController extends AllowController{
    /*
     * 构造函数
     *
     * @return  #
     */
    public function _initialize(){       
        parent::_initialize();
        $this->db_clubGroup =D("ClubGroup");
        $this->db_club      =D("Club");
        $this->db_reply     =D("Reply"); 
        $this->user         =D("User");
        $this->im           =D("Im");
    }
    
    /*
     * 俱乐部列表
     * 
     * @return #
     */
    public function index(){       
        if(I("uid","","code")){
            $uid    =I("uid","","code");
            $cList  =$this->db_clubGroup->where(array("status"=>1))->select();
            $clubIds=array();
            foreach($cList as $k){
                if(in_array($uid,  explode(",",$k['user_ids'] ))){
                    $clubIds[]=$k['id'];
                }
            }
            if(!empty($clubIds)){
                $where['id']    =array("in",$clubIds);
                $where['status']=1;
            }
        }        
        $clubGroup  =$this->db_clubGroup->where($where)->select();
        $this->assign("cGroup",$clubGroup);
        $this->display();
    }
    
    /*
     * EVENTS活动列表
     * 
     * @return  #
     */
    public function activityList(){
        $this->actList();
        $this->display();
    }
    
    /*
     * 俱乐部活动列表
     * 
     * @return #
     */
    public function activInfoList(){
        $group_id   =I("request.group_id","","code"); 
        $clubInfo   =$this->db_clubGroup->find($group_id);
        if(in_array(session("home.id"),explode(",",$clubInfo['no_read_ids']))){
            $where['no_read_ids']   =str_replace(session("home.id").',','',$clubInfo['no_read_ids']);
            $where['id']            =$group_id;
            $this->db_clubGroup->save($where);
        }
        if($clubInfo['user_ids']){
            $userList   =$this->user->where(array("id"=>array("in",$clubInfo['user_ids']),'status'=>1))->select();
        }        
        //判断是否已经加入该俱乐部
        $status         =M("UserClub")->where(array("uid"=>session('home.id'),"gclub_id"=>$group_id))->getField("status");
        if($status){
            $this->assign("status",$status);
        }
        $this->actList();
        $this->assign("userList",$userList);
        $this->assign("clubInfo",$clubInfo);
        $this->display("activityList");
    }
    
    /*
     * 活动详情
     * 
     * @return  #
     */
    public function activityInfo(){
        $where=array(
            "id"        =>I("request.id","","code"),
            "status"    =>1
        );
        $activityInfo   =$this->db_club->where($where)->find();
        //查询所属俱乐部
        if($activityInfo['type']==1){
            $clubInfo   =$this->db_clubGroup->find($activityInfo['group_id']);
            //修改未读人员名单，将自己的题为已读
            if(in_array(session("home.id"),explode(",",$clubInfo['no_read_ids']))){
                $where['no_read_ids']   =str_replace(session("home.id").',','',$clubInfo['no_read_ids']);
                $where['id']            =$group_id;
                $this->db_clubGroup->save($where);
            }
        }        
        /*回复主题列表 start*/
        $where1=array(
            "status"        =>1,
            "club_id"       =>I("request.id","","code"),
            "accept_user_id"=>0
        );
        $replyThemeList     =$this->db_reply->where($where1)->select();
        /*回复主题列表 end*/
        /*回复指定人列表 start*/
        $where2=array(
            "status"        =>1,
            "club_id"       =>I("request.id","","code"),
            "accept_user_id"=>array("neq",0)
        );
        $replyConList       =$this->db_reply->where($where2)->select();
        /*回复指定人列表 end*/
        /*参与该活动成员列表 start*/
        if($activityInfo['activity_ids']){
            $where3=array(
                "status"    =>1,
                "id"        =>array("in",$activityInfo['activity_ids'])
            );
            $users          =$this->user->where($where3)->select(array('field' =>"id,name,image"));
            $this->assign("users",$users);
        }        
        /*参与该活动成员列表 end*/
        //判断是否已经加入该活动
        $status     =M("UserClub")->where(array("uid"=>session('home.id'),"club_id"=>$where['id']))->getField("status");
        if($status){
            $this->assign("status",$status);
        }
        $this->assign("replyThemeList",$replyThemeList);
        $this->assign("replyConList",$replyConList);
        $this->assign("activityInfo",$activityInfo);        
        $this->display();
    }
    
    /*
     * ajax编辑活动
     * 
     * @return #
     */
    public function ajaxEdit(){
        $id =I("request.id",'',"int");
        $activeInfo =$this->db_club->find($id);
        $this->ajaxReturn($activeInfo['theme']);
    }
        
    /*
     * 删除指定活动
     * 
     * @return bool 
     */
    public function delActivity(){
        $group_id   =I("request.group_id","","code");
        $type       =I("request.type","","code");
        if(!I("request.id","","code")){
            if($group_id){
                $this->error("参数错误",U("activInfoList",array("group_id"=>code($group_id,1),"type"=>code($type,1))));
            }
           $this->error("参数错误",U('activityList')); 
        }        
        $data=array(
            "id"        =>I("request.id","","code"),
            'status'    =>0
        );
        $delActivity    =$this->db_club->save($data);
        if($delActivity){     
            //查找该活动参与人id
            $activityInfo   =$this->db_club->field('activity_ids,theme')->find($data['id']);
            $user['id']     =array("in",trim(str_replace($_SESSION['home']['id'].',', '', $activityInfo['activity_ids'])));
            //为每个参与人添加信息提示
            $this->user->where($user)->setInc("system_num");
            //给每个参与人发送取消互动通知
            $accept_user_id =explode(',', trim($activityInfo['activity_ids'],','));
            foreach($accept_user_id as $v){
                $where2=array(
                    "accept_user_id"=>$v,
                    "content"       =>I("request.name","","code")." ".'退出'." " .$activityInfo['theme'],
                    'active_id'     =>I("request.id","","code"),
                    'type'          =>4
                );
                $this->im->add($where2);
            }
            if($group_id){
                redirect(U("activInfoList",array("group_id"=>code($group_id,1),"type"=>code($type,1))));
            }else{
                redirect(U("activityList",array("type"=>code($type,1))));
            }            
        }        
    }
    
    
    /*
     * 新增活动，
     * 
     * @return  #
     */
    public function addActivity(){
        if(I("post.title")){
            if(session("lang")==1){
                $where['en_theme']  =I("post.title","","trim");
            }else{
                $where['theme']     =I("post.title","","trim");
            }
        }
        if(I("post.validity")){
            //$where['validity']      =strtotime(I("post.validity","","trim"));
            $where['validity']      =str_replace('/','-',I("request.validity"));
        }
        if($_POST['content']){    
            if(session("lang")==1){
                $where['en_content']=I("post.content","",'trim');
            }else{
                $where['content']   =I("post.content","",'trim');
            }
        }
        if(I("post.type")){
            $where['type']          =I("post.type","","int");
        }
        if(I("post.group_id")){
            $where['group_id']      =I("post.group_id","","int");
        }
        $where['assign_user_id']    =session('home.id');
        $addActivity                =$this->db_club->add($where);
        if($addActivity){
            if($where['type']){
                if($where['type']==1){
                    //表示新增的是俱乐部活动，为俱乐部加红点
                    $club_ids   =$this->db_clubGroup->where(array("id"=>I("request.group_id")))->getField("user_ids");
                    //为每个人小红点
                    $where1=array(
                        "id"            =>$where['group_id'],
                        'no_read_ids'   =>$club_ids,
                    );
                    $this->db_clubGroup->where($where1)->save();
                }
                $type_      =code((string)$where['type'],1);
                $group_id   =code((string)$where['group_id'],1);
                redirect(U("activInfoList",array('type'=>$type_,'group_id'=>$group_id)));
            }else{
                redirect("activityList");
            }
        }else{
            $this->error("添加活动失败");
        }
    }
    
    /*
     * 活动列表
     * 
     * @return #
     */
    public function actList(){
        $where=array(
            "status"=>1
        );
        if(I("request.type","","code")){
            $where['type']  =I("request.type","","code");
        }else{
            $where['type']  =1;
        }
        if(I("request.group_id","","code")){
            $where['group_id']=I("request.group_id","","code");
        }
        $ord['add_time']=desc;
        $activityInfo   =$this->db_club->clubList($where,$ord,10,1);
        $activityList   =$activityInfo['clubList'];
        $pageList       =$activityInfo['pageList'];
        /*
        if(strpos($pageList,"首")){
            $pageList=str_replace("首 页", "First", $pageList);            
        }
        if(strpos($pageList,"上")){
            $pageList=str_replace("上一页", "Prev", $pageList);
        }
        if(strpos($pageList,"下")){
            $pageList=str_replace("下一页", "Next", $pageList);
        }
        if(strpos($pageList,"尾")){
            $pageList=str_replace("尾 页", "Last", $pageList);
        }
         * 
         */
        $this->assign("activityList",$activityList);
        $this->assign("pageList",$pageList);
        $this->assign("type",$where['type']);
        $this->assign("group_id",$where['group_id']);
    }
    
    /*
     * 编辑活动
     * 
     * @return #
     */
    public function edit_reply(){
        if(I("request.content","","trim")){
            if(session('lang')==1){
                $map['en_content']  =I("request.content","","trim"); 
            }else{
                $map['content']     =I("request.content","","trim"); 
            }            
        }
        if(I("request.theme","","trim")){
            if(session('lang')==1){
                $map['en_theme']    =I("request.content","","trim"); 
            }else{
                $map['theme']       =I("request.theme","","trim");
            }
             
        }
        if(I("request.validity")){
            $map['validity']        =str_replace('/','-',I("request.validity")); 
        }
        if(I("request.active_id","","int")){
            $map['club_id']         =I("request.active_id","","int");
        }        
        $map['assign_user_id']  =session('home.id');
        if(I("request.type",'',"int")<4){
            //type小于4 ，为编辑event，俱乐部活动或者部门活动
            if(I("request.active_id","","int")){
                $map['id']      =I("request.active_id","","int");
            }            
            $editAc =$this->editActive($map);
            if(!$editAc){
                redirect($_SERVER['HTTP_REFERER']);
            }else{
                $activity_ids   =$this->db_club->field("theme,activity_ids")->find($map['id']);
                $user['id']     =array("in",trim(str_replace($_SESSION['home']['id'].',', '', $activity_ids['activity_ids'])));
                //为每个参与人添加信息提示(除了自己)
                $this->user->where($user)->setInc("system_num");
                //给每个参与人发送更改活动的通知
                $accept_user_id =explode(',', trim($activity_ids['activity_ids'],','));
                foreach($accept_user_id as $v){
                    $where2=array(
                        "accept_user_id"=>$v,
                        "content"       =>session('home.name')." ".'修改'." " .$activity_ids['theme'],
                        'active_id'     =>$map['club_id'],
                        'type'          =>1
                    );
                    $this->im->add($where2);
                }
                redirect($_SERVER['HTTP_REFERER']);
            }
        }else if(I("request.type",'',"int")==4){
            //type为4表示回复的是主题
            $map['path_id'] =session('home.id').'-';
            $map['sign']    =time();
            $this->replyActive($map);
            redirect($_SERVER['HTTP_REFERER']);
        }else if(I("request.type",'',"int")==5){
            //type为5表示回复某人
            if(I("request.reply_id","","int")){
                $old_path_id            =$this->db_reply->field('path_id,sign')->find(I("request.reply_id","","int"));
                $map['path_id']         =$old_path_id['path_id'].session('home.id').'-';
                $map['sign']            =$old_path_id['sign'].'a';
            }            
            if(I("request.accept_user_id",'','int')){
                $map['accept_user_id']  =I("request.accept_user_id",'','int');
            }
            $this->replyActive($map);
            redirect($_SERVER['HTTP_REFERER']);
        }
    }
    
    /*
     * 编辑活动
     * 
     * @return #
     */
    public function editActive($where){
        //$acInfo =$this->db_club->field("group_id,type")->find($where['id']);
        if($this->db_club->save($where)){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    /*
     * 添加回复
     * 
     * #return #
     */
    public function replyActive($where){        
        if($this->db_reply->add($where)){
            if(!$where['access_user_id']){
                //说明回复的是主题，根据活动id查询发布人
                $user_id=$this->db_club->field("assign_user_id,theme")->find($where['club_id']);
                //给活动发布人发送消息
                $this->user->where(array("id"=>$user_id['assign_user_id']))->setInc("system_num");
                $where1=array(
                    "accept_user_id"=>$user_id['assign_user_id'],
                    "content"       =>session('home.name')." ".'回复了你主题为'." " .$user_id['theme'].' 的活动',                   
                    'active_id'     =>$where['club_id'],
                    'type'          =>1
                );
                $this->im->add($where1);
            }else{
                $this->user->where(array("id"=>$where['access_user_id']))->setInc("system_num");
                $where1=array(
                    "accept_user_id"=>$where['access_user_id'],
                    "content"       =>session('home.name')." ".'恢复了你主题为'." " .$user_id['theme'].' 的活动',                   
                    'active_id'     =>$where['club_id'],
                    'type'          =>1
                );
                $this->im->add($where1);
            }
        }
    }
    
    /*
     * 删除活动回复
     * 
     * @return bool
     */
    public function delReply(){
        $data=array(
            "id"        =>I("request.id","","code"),
            'status'    =>0
        );
        $this->db_reply->save($data);
        redirect($_SERVER['HTTP_REFERER']);
    }
    
    /*
     * 加入活动
     * 
     * @return str
     */
    public function ajaxActive(){
        $id     =I("request.id","","int");
        $type   =I("request.type","","int");
        $info   =$this->db_club->field("assign_user_id,theme")->find($id);//活动信息
        $user   =$this->user->where(array("id"=>session("home.id")))->getField("name");
        $message="申请加入活动";
        if($type==3){
            //等于3为EVENTS，每个人都可以申请加入加入            
            $this->addSuccess($info,$user,$id,$message,2,2);            
        }else if($type==2){
            //type等于2为部门活动，只有部门人员可以参加
            //根据id查询部门
            $group_id       =$this->db_club->where(array("id"=>$id))->getField("group_id");
            //查询申请人是否在部门中
            $user_section   =$this->user->where(array("id"=>session("home.id")))->getField("section_id");
            if($group_id!=$user_section){
                $this->ajaxReturn(2);//部门活动，非部门员工不能参与
            }else{
                $this->addSuccess($info,$user,$id,$message,2);
                //提交申请，等待审核
            }
        }else if($type==1){
            $group_id   =$this->db_club->where(array("id"=>$id))->getField("group_id");
            $user_ids   =$this->db_clubGroup->where(array("id"=>$group_id))->getField("user_ids");    
            if(!strpos($user_ids,session("home.id"))){
                $this->ajaxReturn(3);//俱乐部活动，请先申请加入俱乐部
            }else{
                //提交申请，等待审核
                $this->addSuccess($info,$user,$id,$message,2,2);              
            }
        }
    }
    
    /*
     * 活动参加成功公用函数
     * 
     * #return #
     */
    public function addSuccess($info,$user,$id,$message,$sign,$type,$is_out){
        if($info['theme']){
            $com=$info['theme'];            
        }else{
            $com=$info['name'];
            $data['is_gclub']   =1;
        }
        $data=array(
            'accept_user_id'=>$info['assign_user_id'],
            "content"       =>$user.' '.$message.' '.$com,
            "type"          =>$type,
            "assign_user_id"=>session("home.id"),
        );
        if($is_out){
            $data['is_out'] =1; 
        }
        $this->im->add($data); 
        $this->user->where(array("id"=>$info['assign_user_id']))->setInc("system_num");
        $map['uid']     =session("home.id");        
        $map['status']  =2;
        if($sign==1){
            $map['club_id'] =$id;
            M("UserClub")->save($map);
        }else if($sign==2){
            $map['club_id'] =$id;
            M("UserClub")->add($map);
        }else if($sign==3){
            $map['gclub_id']=$id;
            M("UserClub")->add($map);
        }else if($sign==4){
            $map['gclub_id']=$id;
            M("UserClub")->save($map);
        }        
        $this->ajaxReturn(1);
    }
    
    /*
     * 退出活动
     * 
     * @return ajaxReturn bool
     */
    public function ajaxOut(){
        $message="申请退出活动";
        $id =I("post.id","","int");
        $info   =$this->db_club->field("assign_user_id,theme")->find($id);//活动信息
        $user   =$this->user->where(array("id"=>session("home.id")))->getField("name");
        $this->addSuccess($info,$user,$id,$message,1,2,1);
    }
    
    /*
     * 申请加入俱乐部
     * 
     * @return  ajaxReturn 
     */
    public function ajaxAddClub(){
        $id     =I("post.id",'','int');
        $info   =$this->db_clubGroup->field("name,assign_user_id")->find($id);
        $user   =$this->user->where(array("id"=>session("home.id")))->getField("name");
        $message="申请加入俱乐部 ";                   
        $this->addSuccess($info,$user,$id,$message,3,2); 
    }
    
    /*
     * 申请退出俱乐部
     * 
     * @return str
     */
    public function ajaxOutClub(){
        $message="申请退出俱乐部";
        $id =I("post.id","","int");
        $info   =$this->db_clubGroup->field("name,assign_user_id")->find($id);
        $user   =$this->user->where(array("id"=>session("home.id")))->getField("name");
        $this->addSuccess($info,$user,$id,$message,4,2,1); 
    }
}
